package com.huan.vertxle.router;

import com.huan.vertxle.service.IScanCodeService;
import com.huan.vertxle.service.impl.ScanCodeServiceImpl;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Slf4JLoggerFactory;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;

/**
 * 用户路由
 *
 * @author huan
 */
public class WebRouter {
  private final InternalLogger logger = Slf4JLoggerFactory.getInstance(this.getClass());

  public Router router;
  private final IScanCodeService scanCodeService;

  public WebRouter() {
    scanCodeService = new ScanCodeServiceImpl();
    createRouter();
  }

  private void createRouter() {
    // web路由
    router = Router.router(Vertx.currentContext().owner());
    // post请求要获取body中内容 需要先调用这个handler预先处理
    router.post("/scanning/code").handler(BodyHandler.create()).handler(scanCodeService::processingScan);
    router.get("/hello").respond(requestHandler -> Future.succeededFuture(new JsonObject().put("Hello", " Vertx!")));
    // 记录router中报500异常的信息
    router.errorHandler(500, routingContext -> {
      logger.error("服务器异常:", routingContext.failure());
    });
  }
}
